package com.acoffee.java.dynamicProxyExer;

import org.junit.jupiter.api.Test;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author acoffee
 * @create 2021-11-16 13:56
 */
//测试类
public class JdkDynamicTest {
    @Test
    public void testJdk(){
        CookieService cookieService = new CookieServiceImpl();
        JdkDynamicProxy jdkDynamicProxy = new JdkDynamicProxy();
        CookieService proxyObject = (CookieService) jdkDynamicProxy.getProxyObject(cookieService);
        proxyObject.cooking();
    }
}

//接口类
interface CookieService{
    void cooking();
}

//实现类
class CookieServiceImpl implements CookieService{

    @Override
    public void cooking() {
        System.out.println("煮饭！");
    }

}

//JDK代理类
class JdkDynamicProxy{
    public Object getProxyObject(Object targetClass){
        Object proxyInstance = Proxy.newProxyInstance(targetClass.getClass().getClassLoader(), targetClass.getClass().getInterfaces(),
                //InvocationHandler：我们这里使用lambda表达式，他是一个函数式接口
                (Object proxy, Method method, Object[] args) -> {
                    System.out.println("洗菜！");
                    Object invoke = method.invoke(targetClass, args);
                    System.out.println("洗碗!");
                    return invoke;
                });
        return proxyInstance;
    }
}
